package com.siam.package_rider.service_impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.siam.package_common.constant.Quantity;
import com.siam.package_common.entity.BasicResult;
import com.siam.package_common.exception.StoneCustomerException;
import com.siam.package_merchant.entity.Merchant;
import com.siam.package_order.feign.WxPayFeignApi;
import com.siam.package_rider.cache.RiderSessionManager;
import com.siam.package_rider.entity.TbRider;
import com.siam.package_rider.entity.TbRiderBill;
import com.siam.package_rider.entity.TbRiderWithdrawRecord;
import com.siam.package_rider.mapper.TbRiderWithdrawRecordMapper;
import com.siam.package_rider.model.param.TbRiderWithdrawRecordParam;
import com.siam.package_rider.service.TbRiderBillService;
import com.siam.package_rider.service.TbRiderService;
import com.siam.package_rider.service.TbRiderWithdrawRecordService;
import com.siam.package_rider.util.TokenUtil;
import com.siam.package_user.entity.MemberTradeRecord;
import com.siam.package_user.feign.MemberTradeRecordFeignApi;
import com.siam.package_weixin_pay.entity.TransferToUserRequest;
import com.siam.package_weixin_pay.entity.TransfersDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * ---------------------------
 * 骑手提现记录表 (TbRiderWithdrawRecordServiceImpl)         
 * ---------------------------
 * 作者：  高品
 * 时间：  2025-03-29 18:55:18
 * ---------------------------
 */
@Service
public class TbRiderWithdrawRecordServiceImpl extends ServiceImpl<TbRiderWithdrawRecordMapper, TbRiderWithdrawRecord> implements TbRiderWithdrawRecordService {

	@Autowired
	private TbRiderWithdrawRecordMapper tbRiderWithdrawRecordMapper;

	@Autowired
	private TbRiderService tbRiderService;

	@Autowired
	private WxPayFeignApi wxPayFeignApi;

	@Autowired
	private MemberTradeRecordFeignApi memberTradeRecordFeignApi;

	@Autowired
	private TbRiderBillService tbRiderBillService;

	@Autowired
	private RiderSessionManager riderSessionManager;

	@Override
	public void insert(TbRiderWithdrawRecordParam param) {
		TbRiderWithdrawRecord record = new TbRiderWithdrawRecord();
		BeanUtils.copyProperties(param, record);
        tbRiderWithdrawRecordMapper.insert(record);
	}

	@Override
	public void delete(Long id) {
		tbRiderWithdrawRecordMapper.deleteById(id);
	}

	@Override
	public void batchDelete(List<Long> idList) {
		tbRiderWithdrawRecordMapper.deleteBatchIds(idList);
	}

	@Override
	public void update(TbRiderWithdrawRecordParam param) {
		TbRiderWithdrawRecord record = new TbRiderWithdrawRecord();
		BeanUtils.copyProperties(param, record);
		tbRiderWithdrawRecordMapper.updateById(record);
	}

	@Override
	public Page<TbRiderWithdrawRecord> page(TbRiderWithdrawRecordParam param) {
        Page<TbRiderWithdrawRecord> page = tbRiderWithdrawRecordMapper.page(new Page(param.getPageNo(), param.getPageSize()), param);
        return page;
	}

	@Override
	public TbRiderWithdrawRecord findById(Long id) {
		return tbRiderWithdrawRecordMapper.selectById(id);
	}

	@Override
	public void auditApplyWithdraw(TbRiderWithdrawRecordParam param) {
		BasicResult basicResult = new BasicResult();

		if(param.getStatus() == Quantity.INT_2 && StringUtils.isBlank(param.getOpinion())){
			throw new StoneCustomerException("审核不通过时，审核意见不能为空");
		}

		TbRiderWithdrawRecord dbTbRiderWithdrawRecord = this.getById(param.getId());
		if(dbTbRiderWithdrawRecord.getAuditStatus() != Quantity.INT_1){
			throw new StoneCustomerException("该提现记录的审核状态错误");
		}

		TbRider dbTbRider = tbRiderService.getById(dbTbRiderWithdrawRecord.getRiderId());

		//TODO-进行提现操作
		if(param.getStatus() == Quantity.INT_1){
			//审核通过
			String orderNo = dbTbRiderWithdrawRecord.getOutTradeNo();

			// 商家转账到零钱
			TransferToUserRequest request = constructTransferToUserRequest(dbTbRiderWithdrawRecord, dbTbRider, orderNo);
			JSONObject transferJsonObject = wxPayFeignApi.payToBalanceV3(request).getData();
			if(transferJsonObject == null){
				throw new StoneCustomerException("打款失败，请联系管理员");
			}

			// 组装extinfo
			Map<String, Object> extInfo = dbTbRiderWithdrawRecord.getExtInfo() == null ? new HashMap<>() : JSON.parseObject(dbTbRiderWithdrawRecord.getExtInfo(), Map.class);
			extInfo.put("requestMerchantTransferParams", transferJsonObject);

			//修改商家申请信息
			TbRiderWithdrawRecord updateTbRiderWithdrawRecord = new TbRiderWithdrawRecord();
			updateTbRiderWithdrawRecord.setId(param.getId());
			updateTbRiderWithdrawRecord.setAuditStatus(TbRiderWithdrawRecord.AUDIT_STATUS_PAYMENT_PROCESSING);
			updateTbRiderWithdrawRecord.setAuditTime(new Date());
			updateTbRiderWithdrawRecord.setExtInfo(JSON.toJSONString(extInfo));
			updateTbRiderWithdrawRecord.setUpdateTime(new Date());
			this.updateById(updateTbRiderWithdrawRecord);

		}else if(param.getStatus() == Quantity.INT_2){
			//审核不通过
			//修改商家申请信息
			TbRiderWithdrawRecord updateTbRiderWithdrawRecord = new TbRiderWithdrawRecord();
			updateTbRiderWithdrawRecord.setId(param.getId());
			updateTbRiderWithdrawRecord.setAuditStatus(TbRiderWithdrawRecord.AUDIT_STATUS_FAIL);
			updateTbRiderWithdrawRecord.setAuditReason(param.getOpinion());
			updateTbRiderWithdrawRecord.setAuditTime(new Date());
			updateTbRiderWithdrawRecord.setUpdateTime(new Date());
			this.updateById(updateTbRiderWithdrawRecord);

			// 提现失败后置处理
			handleWithdrawFail(dbTbRiderWithdrawRecord, dbTbRider);
		}
	}

	public void handleWithdrawFail(TbRiderWithdrawRecord dbTbRiderWithdrawRecord, TbRider dbTbRider) {
		//退回商家提现扣除的金额
		BigDecimal totalAmount = dbTbRiderWithdrawRecord.getActualAmount().add(dbTbRiderWithdrawRecord.getPlatformFee()).setScale(2, BigDecimal.ROUND_HALF_UP);

		//增加商家的余额
		BigDecimal updateBalance = dbTbRider.getBalance().add(totalAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
		;

		BigDecimal updateWithdrawableBalance = dbTbRider.getWithdrawableBalance().add(totalAmount).setScale(2, BigDecimal.ROUND_HALF_UP);
		;

		TbRider updateTbRider = new TbRider();
		updateTbRider.setId(dbTbRider.getId());
		updateTbRider.setBalance(updateBalance);
		updateTbRider.setWithdrawableBalance(updateWithdrawableBalance);
		updateTbRider.setUpdateTime(new Date());
		tbRiderService.updateById(updateTbRider);

		//增加商家账单记录
		TbRiderBill tbRiderBillingRecord = new TbRiderBill();
		tbRiderBillingRecord.setRiderId(dbTbRiderWithdrawRecord.getRiderId());
		tbRiderBillingRecord.setType(Quantity.INT_3);
		tbRiderBillingRecord.setOperateType(Quantity.INT_1);
		tbRiderBillingRecord.setCoinType(Quantity.INT_1);
		tbRiderBillingRecord.setNumber(totalAmount);
		tbRiderBillingRecord.setMessage("商家提现失败退回 -- 订单号" + dbTbRiderWithdrawRecord.getOutTradeNo());
		tbRiderBillingRecord.setCreateTime(new Date());
		tbRiderBillService.save(tbRiderBillingRecord);

		//TODO-发消息通知用户
	}

	/**
	 * 企业付款到零钱-组装参数【已废弃，微信官方不再支持该功能】
	 * @param dbTbRiderWithdrawRecord
	 * @param dbTbRider
	 * @param orderNo
	 * @return
	 */
	private TransfersDto constructTransfersDto(TbRiderWithdrawRecord dbTbRiderWithdrawRecord, TbRider dbTbRider, String orderNo) {
		TransfersDto transfersDto = new TransfersDto();
		transfersDto.setOpenid(dbTbRider.getOpenId());
		transfersDto.setAmount(dbTbRiderWithdrawRecord.getWithdrawAmount().doubleValue());
		transfersDto.setRe_user_name(dbTbRider.getRealName());
		transfersDto.setPartner_trade_no(orderNo);
		transfersDto.setDesc("高品外卖-骑手提现到账");
		return transfersDto;
	}

	/**
	 * 商家转账到零钱-组装参数
	 * @param dbTbRiderWithdrawRecord
	 * @param dbTbRider
	 * @param orderNo
	 * @return
	 */
	private TransferToUserRequest constructTransferToUserRequest(TbRiderWithdrawRecord dbTbRiderWithdrawRecord, TbRider dbTbRider, String orderNo) {
		// TODO: 请准备商户开发必要参数，参考：https://pay.weixin.qq.com/doc/v3/merchant/4013070756
		TransferToUserRequest request = new TransferToUserRequest();
		request.outBillNo = orderNo;
		request.transferSceneId = "1005"; // 根据商户申请的类别来填
		request.openid = dbTbRider.getOpenId();
		request.setUserName(dbTbRider.getRealName());
		request.transferAmount = dbTbRiderWithdrawRecord.getWithdrawAmount().multiply(BigDecimal.valueOf(100)).longValue();
		request.transferRemark = "高品外卖-骑手余额提现";
		request.transferSceneReportInfos = new ArrayList<>();
		{
			TransferToUserRequest.TransferSceneReportInfo item0 = new TransferToUserRequest.TransferSceneReportInfo();
			item0.infoType = "岗位类型";
			item0.infoContent = "-";
			request.transferSceneReportInfos.add(item0);
			TransferToUserRequest.TransferSceneReportInfo item1 = new TransferToUserRequest.TransferSceneReportInfo();
			item1.infoType = "报酬说明";
			item1.infoContent = "-";
			request.transferSceneReportInfos.add(item1);
		};
		return request;
	}

	@Override
	public Map<String, Object> statisticalAmount(TbRiderWithdrawRecordParam param) {
		TbRider loginTbRider = riderSessionManager.getSession(TokenUtil.getToken());
		if(loginTbRider != null){
			param.setRiderId(loginTbRider.getId());
		}

		BigDecimal withdrawalSuccessfulAmount = tbRiderWithdrawRecordMapper.statisticalAmountByWithdrawalSuccessful(param);

		Map<String, Object> map = new HashMap<>();
		map.put("withdrawalSuccessfulAmount", withdrawalSuccessfulAmount);
		return map;
	}
}